package org.example.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class ExcelReader {
    public static Map<String, String> readExcel(String filePath) throws IOException {
        Map<String, String> data = new HashMap<>();
        FileInputStream fis = new FileInputStream(new File(filePath));
        Workbook workbook = new XSSFWorkbook(fis);
        Sheet sheet = workbook.getSheetAt(0); // 假设数据在第一个Sheet

        Row firstRow = sheet.getRow(0); // 假设第一行是标题行
        int nameXzqhIndex = getFirstColumnIndex(firstRow, "nameXzqh");
        int nameZhIndex = getFirstColumnIndex(firstRow, "nameZh");
        int nameHyIndex = getFirstColumnIndex(firstRow, "nameHy");
        int nameZzxsIndex = getFirstColumnIndex(firstRow, "nameZzxs");
        int S_PROLOCIndex = getFirstColumnIndex(firstRow, "S_PROLOC");
        int zyywIndex = getFirstColumnIndex(firstRow, "zyyw");
        int S_DOM_LOCATIONIndex = getFirstColumnIndex(firstRow, "S_DOM_LOCATION");


        Row dataRow = sheet.getRow(1); // 假设第二行是数据行
        if (dataRow != null) {
            data.put("nameXzqh", dataRow.getCell(nameXzqhIndex).getStringCellValue());
            data.put("nameZh", dataRow.getCell(nameZhIndex).getStringCellValue());
            data.put("nameHy", dataRow.getCell(nameHyIndex).getStringCellValue());
            data.put("nameZzxs", dataRow.getCell(nameZzxsIndex).getStringCellValue());
            data.put("S_PROLOC", dataRow.getCell(S_PROLOCIndex).getStringCellValue());
            data.put("zyyw", dataRow.getCell(zyywIndex).getStringCellValue());
            data.put("S_DOM_LOCATION", dataRow.getCell(S_DOM_LOCATIONIndex).getStringCellValue());




        }

        workbook.close();
        fis.close();
        return data;
    }

    private static int getFirstColumnIndex(Row row, String columnName) {
        for (int i = 0; i < row.getLastCellNum(); i++) {
            Cell cell = row.getCell(i);
            if (cell != null && cell.getCellType() == CellType.STRING && cell.getStringCellValue().equals(columnName)) {
                return i;
            }
        }
        return -1; // 如果找不到，返回-1
    }

}
